package com.verlet.springbootdemo.filter;

import com.verlet.springbootdemo.annotation.IgnoreAuth;
import com.verlet.springbootdemo.common.ResponseCode;
import com.verlet.springbootdemo.entity.User;
import com.verlet.springbootdemo.execption.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

/**
 * @author verlet
 * @date 2020/4/9
 */
@Slf4j
public class IgnoreAuthInterceptor implements HandlerInterceptor {

    /**
     * 测试数据
     */
    public static final User USER = new User(1L, "test", "123");
    public static final String TOKEN = "758951123";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("{} ======== {} 开始进入请求地址拦截========", Thread.currentThread(), request.getRequestURI());

        // 用来处理静态资源的
        if(handler instanceof ResourceHttpRequestHandler){
            return true;
        }
        String token = request.getHeader("token");
        IgnoreAuth ignoreAuth = null;
        // springMVC中用@Controller声明的一个bean及对应的处理方法
        if (handler instanceof HandlerMethod handlerMethod) {
            ignoreAuth = handlerMethod.getMethodAnnotation(IgnoreAuth.class);
        }
        if (ignoreAuth != null || (StringUtils.isNotBlank(token) && TOKEN.equals(token))) {
            return true;
        }
        throw new BizException(ResponseCode.NEED_LOGIN, "请先登录");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("{} ======== {} 处理请求完成后视图渲染之前的处理操作====== ", Thread.currentThread(), request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("{} ======== {} 视图渲染之后的操作======", Thread.currentThread(), request.getRequestURI());
    }
}
